package com.anolesoft.yr.mbus.cont.ctrl;

import cn.hutool.core.util.StrUtil;
import com.anolesoft.common.core.web.domain.AjaxResult;
import com.anolesoft.common.core.web.page.TableDataInfo;
import com.anolesoft.yr.mbus.base.dto.BaseCompanyDTO;
import com.anolesoft.yr.mbus.base.service.BaseCompanyService;
import com.anolesoft.yr.mbus.base.vo.BaseCompanyVO;
import com.anolesoft.yr.mbus.cont.dto.ContKeyCustomerMainInsertDto;
import com.anolesoft.yr.mbus.cont.entity.*;
import com.anolesoft.yr.mbus.cont.service.ContKeyCustomerMainService;
import com.anolesoft.yr.mbus.cont.service.ContMainService;

import com.anolesoft.yr.mbus.contm.util.FileUtils;
import com.anolesoft.yr.mbus.crm.dto.CrmBaseDTO;
import com.anolesoft.yr.mbus.crm.service.CrmBaseService;
import com.anolesoft.yr.mbus.crm.vo.CrmBaseVO;
import com.anolesoft.yr.store.stk.util.StringUtil;
import com.anolesoft.yr.util.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangcong
 * @Date 20201015
 */
@AllArgsConstructor
@RestController
@RequestMapping("/cont/cont_key_customer_main")
public class ContKeyCustomerMainController {

    private ContKeyCustomerMainService contKeyCustomerMainService;
    private ContMainService contMainService;
    @PostMapping(value = "/add", produces = {"application/json;charset=UTF-8"})
    @Transactional
    public AjaxResult add(ContKeyCustomerMainInsertDto contKeyCustomerMainInsertDto){
        String fileName = StringUtil.generateRundom32String()+".pdf";
        String objuid = StringUtil.generateRundom32String();
        String path = "e://temp//tempfile//";
        FileUtils.upload(path,fileName,contKeyCustomerMainInsertDto.getFile());
        ContKeyCustomerMain contKeyCustomerMain = ContKeyCustomerMain.builder().contCode(contKeyCustomerMainInsertDto.getContCode()).customerUid(contKeyCustomerMainInsertDto.getCustomerUid())
                .companyUid(contKeyCustomerMainInsertDto.getCompanyUid())
                .cTime(new Date())
                .cUserUid(SecurityUtils.getLoginUser().getEmpUid())
                .path(StrUtil.concat(true, path, fileName))
                .objuid(objuid)
                .build();
        contKeyCustomerMainService.save(contKeyCustomerMain);
        if(contKeyCustomerMainInsertDto.getContMainUids()!=null&&contKeyCustomerMainInsertDto.getContMainUids().size()>0){
            ContMainExample contMainExample = new ContMainExample();
            contMainExample.createCriteria().andObjuidIn(contKeyCustomerMainInsertDto.getContMainUids());
            contMainService.updateByExampleSelective(ContMain.builder().formalContract(contKeyCustomerMainInsertDto.getContCode()).build(),contMainExample);
        }
        return AjaxResult.success("保存成功");
    }
    @RequestMapping(value = "/get", produces = {"application/json;charset=UTF-8"})
    @Transactional
    public AjaxResult get(ContKeyCustomerMain contKeyCustomerMain){
        String companyUid = StrUtil.nullToEmpty(contKeyCustomerMain.getCompanyUid());
        String customerUid = StrUtil.nullToEmpty(contKeyCustomerMain.getCustomerUid());
        String contCode = StrUtil.nullToEmpty(contKeyCustomerMain.getContCode());
        String tempContCode = StrUtil.nullToEmpty(contKeyCustomerMain.getTempContCode());

        if (!"".equals(tempContCode)){
            ContMainExample contMainExample = new ContMainExample();
            contMainExample.createCriteria().andContCodeEqualTo(tempContCode);
            List<ContMain> contMains = contMainService.selectByExample(contMainExample);
            if (contMains.size()>0){
                tempContCode =StrUtil.nullToEmpty(contMains.get(0).getFormalContract()); ;
            }else{
                tempContCode = "没有此合同号";

            }
        }

        LambdaQueryWrapper<ContKeyCustomerMain> like = new QueryWrapper<ContKeyCustomerMain>()
                .lambda()
                .like(ContKeyCustomerMain::getCompanyUid,companyUid)
                .like(ContKeyCustomerMain::getCustomerUid,customerUid)
                .like(ContKeyCustomerMain::getContCode,contCode)
                .orderByDesc(ContKeyCustomerMain::getcTime);
        if (tempContCode!=null&&!"".equals(tempContCode)) {
            like.eq(ContKeyCustomerMain::getContCode, tempContCode);
        }
        Page<ContKeyCustomerMain> page = new Page<>(contKeyCustomerMain.getPage(), contKeyCustomerMain.getRows());
        List<ContKeyCustomerMain> contmStyleMains = contKeyCustomerMainService.selectAll(page, like);

        return  AjaxResult.success(new TableDataInfo(page.getTotal(), contmStyleMains));
    }
    @PostMapping(value = "/download", produces = {"application/json;charset=UTF-8"})
    @Transactional
    public AjaxResult download(String url){
        return AjaxResult.success("保存成功");
    }

    private BaseCompanyService baseCompanyService;
    private CrmBaseService crmBaseService;
    @PostMapping(value = "/company/list/all", produces = MediaType.APPLICATION_JSON_VALUE)
    public List<BaseCompanyVO> companySelectAll(BaseCompanyDTO baseCompanyDTO) {
        List<BaseCompanyVO> vos = baseCompanyService.selectList(baseCompanyDTO).stream().map(t -> CustomBeanUtils.baseCompanyDTO2VO(t)).collect(Collectors.toList());
        return vos;
    }
    @PostMapping(value = "/crm/list/all", produces = MediaType.APPLICATION_JSON_VALUE)
    public List<CrmBaseVO> crmSelectAll(CrmBaseDTO crmBaseDto) {
        List<CrmBaseVO> vos = crmBaseService.selectList(crmBaseDto).stream().map(t -> CustomBeanUtils.crmBaseDTO2VO(t)).collect(Collectors.toList());
        return vos;
    }
    @RequestMapping(value = "/getEdit", produces = MediaType.APPLICATION_JSON_VALUE)
    public ContKeyCustomerMain getEdit(String objuid){
        return contKeyCustomerMainService.getById(objuid);
    }
    @RequestMapping(value = "/edit",produces = {"application/json;charset=UTF-8"})
    @Transactional
    public AjaxResult edit(ContKeyCustomerMainInsertDto contKeyCustomerMainInsertDto){
        ContKeyCustomerMain contKeyCustomerMain = contKeyCustomerMainService.getById(contKeyCustomerMainInsertDto.getObjuid());

        String fileName = StringUtil.generateRundom32String()+".pdf";
        String path = "e://temp";
        if (contKeyCustomerMainInsertDto.getFile()!=null){
            FileUtils.upload(path,fileName,contKeyCustomerMainInsertDto.getFile());
            contKeyCustomerMain.setPath(StrUtil.concat(true, path, fileName));
        }
        ContMainExample contMainExample = new ContMainExample();
        contMainExample.createCriteria().andFormalContractEqualTo(contKeyCustomerMain.getContCode());
        contMainService.updateByExampleSelective(ContMain.builder().formalContract("").build(),contMainExample);
        contKeyCustomerMain.setCompanyUid(contKeyCustomerMainInsertDto.getCompanyUid());
        contKeyCustomerMain.setCustomerUid(contKeyCustomerMainInsertDto.getCustomerUid());
        contKeyCustomerMain.setRemark(contKeyCustomerMainInsertDto.getRemark());
        contKeyCustomerMain.setContCode(contKeyCustomerMainInsertDto.getContCode());

        contKeyCustomerMainService.updateById(contKeyCustomerMain);
        if(contKeyCustomerMainInsertDto.getContMainUids()!=null&&contKeyCustomerMainInsertDto.getContMainUids().size()>0){
            ContMainExample contMainExampleTemp = new ContMainExample();
            contMainExampleTemp.createCriteria().andObjuidIn(contKeyCustomerMainInsertDto.getContMainUids());
            contMainService.updateByExampleSelective(ContMain.builder().formalContract(contKeyCustomerMainInsertDto.getContCode()).build(),contMainExampleTemp);
        }
        return AjaxResult.success("修改成功");
    }

    @RequestMapping(value = "/del",produces = {"application/json;charset=UTF-8"})
    @Transactional
    public AjaxResult del(@RequestBody List<ContKeyCustomerMain> Mains ){
        List<String> objuids = Mains.stream().map(ContKeyCustomerMain::getObjuid).collect(Collectors.toList());
        ContKeyCustomerMainExample contKeyCustomerMainExample = new ContKeyCustomerMainExample();
        contKeyCustomerMainExample.createCriteria().andObjuidIn(objuids);
        List<ContKeyCustomerMain> contKeyCustomerMains = contKeyCustomerMainService.selectByExample(contKeyCustomerMainExample);
        List<String> collect = contKeyCustomerMains.stream().map(ContKeyCustomerMain::getContCode).collect(Collectors.toList());
        ContMainExample contMainExample = new ContMainExample();
        contMainExample.createCriteria().andFormalContractIn(collect);
        contMainService.updateByExampleSelective(ContMain.builder().formalContract("").build(),contMainExample);
        contKeyCustomerMainService.deleteByExample(contKeyCustomerMainExample);
        return AjaxResult.success("删除成功");
    }

    @RequestMapping(value = "/unique",  produces = {"application/json;charset=UTF-8"})
    public boolean unique(String contCode,String objuid){
        objuid = StrUtil.nullToEmpty(objuid);
        ContKeyCustomerMainExample contVariableExample = new ContKeyCustomerMainExample();
        contVariableExample.createCriteria().andContCodeEqualTo(contCode).andObjuidNotEqualTo(objuid);
        List<ContKeyCustomerMain> contKeyCustomerMains = contKeyCustomerMainService.selectByExample(contVariableExample);
        if (!contKeyCustomerMains.isEmpty()) {
            return false;
        }else {
            return true;
        }
    }

}

